package com.hspedu.furns.filter;

import com.hspedu.furns.utils.JDBCUtilsByDruid;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author 徐
 * @version 1.0
 * 保持数据库数据一致性
 * 事务，回滚
 */
public class TransactionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //放行
        try {
            filterChain.doFilter(servletRequest,servletResponse);
            JDBCUtilsByDruid.commit();//同一提交，发生异常
        } catch (Exception e) {
            JDBCUtilsByDruid.rollback();//回滚事务
            //e.printStackTrace();
            //这里改成跑出异常，让tomcat捕获，然后调用500.jsp
            //异常可以参与业务逻辑
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy() {

    }
}
